﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace EasyClass {
	public class Team {
		static private JavaScriptSerializer jss = new JavaScriptSerializer();
		public Topic topic;
		public string teamName;
		public string password;
		public int status; // 0: unlocked, 1: locked
		public string captainID;
		public List<string> members;  //IDs

		public Team(Topic to, string tn, string c, string p) {
			topic = to;
			teamName = tn;
			captainID = c;
			password = p;
			status = 0;
			members = new List<string>();
		}

		public Panel GetPanel(int index) {
			MyConsole.WriteLine("GetPanel: "+teamName);
			FlowLayoutPanel p1 = new FlowLayoutPanel();
			p1.FlowDirection = FlowDirection.TopDown;
			p1.WrapContents = false;
			p1.Width = 300;
			p1.Dock = DockStyle.Left;
			Label l1 = new Label();
			l1.AutoSize = true;
			Label l2 = new Label();
			l2.AutoSize = true;
			Label l3 = new Label();
			l3.AutoSize = true;
			l1.Text = index.ToString() + ". Team Name: " + teamName;
			l2.Text = "Captain ID: " + captainID + "          Status: ";
			if (status == 1)
				l2.Text += "Locked";
			else
				l2.Text += "Unlocked";
			l3.Text = "Members: ";
			foreach (string sID in members) l3.Text += sID + ", ";
			l3.Text.Remove(l3.Text.Length - 2);
			p1.Controls.Add(l1);
			p1.Controls.Add(l2);
			p1.Controls.Add(l3);

			Panel p2 = new Panel();
			p2.Dock = DockStyle.Right;
			p2.Width = 50;
			TeamButton del = new TeamButton(this);
			del.Text = "Delete";
			del.Width = 50;
			del.Click += new EventHandler(topic.DeleteButton_Click);
			p2.Controls.Add(del);

			Panel panel = new Panel();
			panel.Width = 375;
			panel.Controls.Add(p1);
			panel.Controls.Add(p2);
			return panel;
		}

		public bool ContainMember(string studentID) {
			if (captainID == studentID) return true;
			foreach (string sID in members) {
				if (sID == studentID) return true;
			}
			return false;
		}

		public bool TryAddMember(string studentID, ref string reason) {
			if (2 + members.Count > topic.upper) {
				reason = "The team is full";
				return false;
			}
			if (members.Contains(studentID)) {
				reason = "You are already in the team";
				return false;
			}
			members.Add(studentID);
			return true;
		}

		public string ToJSON() {
			Dictionary<string, string> dict = new Dictionary<string, string>();
			dict["TeamName"] = teamName;
			dict["CaptainID"] = captainID;
			dict["Password"] = password;
			dict["Status"] = status.ToString();
			dict["NMembers"] = members.Count.ToString();
			int cnt = 0;
			foreach (string s in members) {
				dict["Member" + cnt++.ToString()] = s;
			}
			return jss.Serialize(dict);
		}

		
	}
}
